<template>
    <view class="page-notice">
        <view class="page-head" :style="{ backgroundColor: pageHeadStyle.backgroundColor }">
            <statusBar></statusBar>
            消息
        </view>
        <view class="head-polyfill" :style="{ height: statusBarHeight + 38 + 'px' }"></view>
        <view class="top-notice" v-if="userInfo.id && !isSubscribeMsg" @click="subscribeMessage" >
            <!-- #ifdef MP -->
            订阅通知
            <image :src="imgBaseUrlV2 + 'arrow.png'"  mode="widthFix"  class="icon"/>
            <!-- #endif -->
        </view>
        <view class="notices" v-if="notices.length">
            <view class="notice" v-for="(notice, noticeIndex) in notices" :key="noticeIndex" @click="viewNotice(notice)">
                <view class="notice-icon-view">
                    <image :lazy-load="true" class="notice-icon" :data-src="imgBaseUrlV1" :src="  imgBaseUrlV2 +  'notice2.png'"  mode="widthFix"></image>
                    <image v-if="!notice.is_read" :lazy-load="true"  class="notice-remind" :src="imgBaseUrlV0 + 'notice-remind.png'" mode="widthFix"></image>
                </view>
                <view class="info-view">
                    <view class="title">
                        <view class="text">
                            {{ notice.title }}
                        </view>
                        <view class="ft">
                            {{ notice.time }}
                        </view>
                    </view>
                    <text class="content">{{ notice.content }}</text>
                </view>
            </view>
        </view>
        <view class="no-data-box" v-if="!notices.length">
            <no-data status="no_xiaoxi" title="暂无相关消息"></no-data>
        </view>
        <view class="tips" v-if="notices.length && listQuery.last"> 已无更多 </view>
        <Message ref="message"></Message>
    </view>
</template>

<script>
import viewModule from "@/common/mixins/view-module";
import { getOperations } from "@/common/api/operation.js";
import { getNoticeList, putRead } from "@/common/api/notice.js";
import { getUserOpenId } from "@/common/api/user.js";
import { mapState } from "vuex";
import noData from "@/components/public/noData/noData";
import {
  imgBaseUrl,
  imgBaseUrlV0,
  imgBaseUrlV1,
  imgBaseUrlV2,
} from "@/common/config";
import statusBar from "@/components/public/status-bar/status-bar";
import { noticeTime } from "@/utils";
const system = uni.getSystemInfoSync();
let statusBarHeight = system.statusBarHeight;
// #ifdef MP-WEIXIN
let custom = uni.getMenuButtonBoundingClientRect();
statusBarHeight = custom.top;
// #endif
export default {
  mixins: [viewModule],
  components: {
    noData,
    statusBar,
  },
  computed: {
    ...mapState("User", ["userInfo"]),
  },
  data() {
    return {
      imgBaseUrl,
      imgBaseUrlV1,
      imgBaseUrlV0,
      imgBaseUrlV2,
      statusBarHeight,
      listQuery: {
        limit: 10,
        page: 1,
		company_id:'',
        clientSide: 1,
        last: false,
      },
      notices: [],
      isSubscribeMsg: true,
      subscribeMsgToast: false,
      noticeTemplateId: "",
      pageHeadStyle: {
        backgroundColor: "#252E43",
        color: "#fff",
      },
    };
  },
  mounted() {
    this.initData();
  },
  methods: {
    onChangePage() {
      if (!this.userInfo.id) {
        this.notices.length = 0;
        this.notices = [];
      }
      if (this.loadingFinish) {
        uni.$emit("hideLoading");
      }
    },
    async pullDownRefresh() {
      uni.$emit("showLoading");
      await this.initData();
      uni.$emit("stopPullDownRefresh");
    },
    reachBottom() {
      if (this.listQuery.last) return;
      this.listQuery.page++;
      this.getNoticeList();
    },
    getUserSettings() {
      // #ifdef MP
      if (this.userInfo.id && this.noticeTemplateId) {
        const that = this;
        // 获取用户的当前设置
        uni.getSetting({
          withSubscriptions: true,
          success: function (res) {
            let itemSettings = res.subscriptionsSetting.itemSettings;
            let noticeTemplateId = that.noticeTemplateId;
            // 如果订阅通知权限没有请求过，则订阅通知
            if (
              itemSettings.length === 0 ||
              itemSettings[noticeTemplateId] === undefined
            ) {
              that.isSubscribeMsg = false;
            } else {
              if (itemSettings[noticeTemplateId] === "accept") {
                that.isSubscribeMsg = true;
              } else {
                if (
                  itemSettings[noticeTemplateId] === "reject" &&
                  that.subscribeMsgToast
                ) {
                  that.message.error("消息订阅已关闭，请从设置进行打开");
                }
                that.subscribeMsgToast = true;
                that.isSubscribeMsg = false;
              }
            }
          },
          fail: function (res) {
            that.isSubscribeMsg = false;
          },
        });
      } else {
        this.isSubscribeMsg = false;
      }
      // #endif
    },
    subscribeMessage() {
      // #ifdef MP
      if (this.userInfo.id && !this.isSubscribeMsg && this.noticeTemplateId) {
        const that = this;

        if (this.userInfo.openId === null || this.userInfo.openId === "") {
          this.getUserOpenId();
        }
        uni.requestSubscribeMessage({
          tmplIds: [this.noticeTemplateId],
          success: function (res) {
            that.getUserSettings();
          },
          fail: function (res) {
            uni.hideLoading();
            console.log("fail", res);
          },
        });
      }
      // #endif
    },
    getUserOpenId() {
      // #ifdef MP
      if (this.userInfo !== "") {
        // 获取code
        uni.login({
          provider: "wexin",
          success: async (res) => {
            // 获取和设置openid
            await getUserOpenId({ id: this.userInfo.id, code: res.code })
              .then((response) => {
                this.userInfo.openId = response;
              })
              .catch(() => {});
          },
          fail: () => {},
          complete: () => {},
        });
      }
      // #endif
    },
    async initData() {
      this.listQuery.last = false;
      if (this.userInfo.id) {
        await Promise.all([this.handleFilter()]);
      }
      this.loadingFinish = true;
      uni.$emit("hideLoading");
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.notices = [];
      return this.getNoticeList();
    },

    getNoticeList() {
      if (this.userInfo.id) {
        if (this.listQuery.page <= 1) {
          uni.$emit("showLoading");
        } else {
          uni.showLoading({
            title: "加载中",
          });
        }
        this.listQuery.company_id = this.userInfo.company_id
        return getNoticeList(this.listQuery)
          .then((res) => {
             
            uni.$emit("hideLoading");
            if (res.code !== this.$ERR_OK)
              return this.message.error(res.message || "获取通知列表失败");
            let data = res.data || {};
            let list = data.data;
            let total = data.total;
            uni.hideLoading();
            list.map((i) => {
              i.time = noticeTime(i.create_time);
            });
            this.notices.push(...list);
           const totalPages = Math.ceil(total / this.listQuery.limit);
           this.listQuery.last = this.listQuery.page >= totalPages; // ✅

            console.log(this.listQuery.last)
            
          })
          .catch(() => {
            uni.hideLoading();
            uni.$emit("hideLoading");
          });
      }
    },

    async viewNotice(notice) {
      this.$Router.push({
        path: "/pages/notice-detail/notice-detail",
        query: {
          id: notice.id,
          // data: encodeURIComponent(JSON.stringify(notice)),
        },
        success: (r) => {
          notice.is_read = true;
        },
      });
    },
  },
};
</script>

<style lang="stylus" scoped>
@import '~@/common/stylus/variable';
@import '~@/common/stylus/mixins';

.page-notice {
  // min-height: calc(100vh - var(--window-top) - 150rpx);
  min-height: calc(100vh - var(--window-top));
  padding-bottom: 50rpx;
  background: #252E43;
}

.top-notice {
  padding: 20rpx 30rpx;
  color: color-white;
  display: flex;
  align-items:center;
  justify-content:space-between;
  font-size: 28rpx;
  background: #1A3156;
  >.icon {
	display: block;
	width: 32rpx;
	margin-left: 6rpx;
  }  
  .left {
    flex: 1;
  }
}

.no-data-box {
  height: calc(100vh - 340rpx);
}

.notices {
  padding-bottom: 50rpx;
  /* #ifdef H5 */
  padding-top: 12rpx;
  background: linear-gradient(180deg, #0D1523 0%, #102945 100%);
  /* #endif */
  .notice {
    display: flex;
    flex-direction: row;
    padding: 0 18rpx;
    background: #1A3156;
    margin: 0 24rpx;
    margin-top: 20rpx;
    border-radius: 10rpx;

    &:last-child {
      margin-bottom: 20rpx;
    }

    .notice-icon-view {
      position: relative;
      margin: auto;

      .notice-icon {
        display: block;
        width: 74rpx;
        height: 74rpx;
      }

      .notice-remind {
        position: absolute !important;
        z-index: 2;
        right: 2rpx;
        top: 2rpx;
        width: 20rpx;
        height: 20rpx;
      }
    }

    .info-view {
      flex: 1;
      padding: 40rpx 0rpx 40rpx 30rpx;

      .title {
        display: flex;
        font-size: 32rpx;
        font-weight: 700;
        padding-bottom: 10rpx;
        color: #fff;

        .text {
          flex: 1;
          no-wrap();
        }

        .ft {
          font-weight: 400;
          font-size: 24rpx;
          color: #fff;
        }
      }

      .content {
        display: block;
        font-size: 26rpx;
        color: #fff;
        overflow: hidden;
        word-break: break-all; /* break-all(允许在单词内换行。) */
        text-overflow: ellipsis; /* 超出部分省略号 */
        display: -webkit-box; /* * 对象作为伸缩盒子模型显示 * */
        -webkit-box-orient: vertical; /* * 设置或检索伸缩盒对象的子元素的排列方式 * */
        -webkit-line-clamp: 1; /* * 显示的行数 * */
      }
    }

    .detail-icon {
      border-bottom: 3rpx solid #eee;
    }

    .ft {
      display: flex;
      align-items: center;

      .iconRight {
        display: block;
        width: 15rpx;
        height: 26rpx;
      }
    }
  }
}

.page-head {
  position: fixed;
  z-index: 998;
  width: 100%;
  line-height: 64rpx;
  left: 0;
  top: 0;
  text-align: center;
  font-size: 36rpx;
  font-family: PingFangSC-Regular, PingFang SC;
  transition: all 0.3s;
  color: #fff;
  background: #252E43;
  // border-bottom: 1rpx solid #eee;
  padding-bottom: 12rpx;
  /* #ifdef H5 */
  padding-top: 12rpx;
  /* #endif */
}
</style>
